package online.niuma.xiaocubao.utils;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * @author 一颗蛋50斤
 * IntelliJ IDEA
 * 邮件发送工具类
 * 异步发送
 */
@Slf4j
@Setter
@Component
public class SendMailUtils {

    @Value("${spring.mail.username}")
    private String fromMail;

    @Resource
    private JavaMailSenderImpl mailSender;

    /**
     * 简单文本邮件
     * @param emailTitle 邮件标题
     * @param emailContent 邮件内容
     * @param toEmail 收件人邮箱
     */
    @Async
    public void sendSimpleMail(String emailTitle, String emailContent, String toEmail) {
        // 创建简单邮件实例
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        // 设置邮件发送人
        mailMessage.setFrom(fromMail);
        // 邮件接收人，一个或多个
        mailMessage.setTo(toEmail.split(","));
        // 设置邮件主题
        mailMessage.setSubject(emailTitle);
        // 设置邮件发送的内容
        mailMessage.setText(emailContent);
        // 设置发送时间
        mailMessage.setSentDate(new Date());
        mailSender.send(mailMessage);
        log.info("邮件发送成功 -> {}", toEmail);
    }

    /**
     * html 文本邮件
     * @param emailTitle 邮件标题
     * @param emailContent 邮件内容
     * @param toEmail 收件人邮箱
     */
    @Async
    public void sendHtmlMail(String emailTitle, String emailContent, String toEmail) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            // 设置发件人
            helper.setFrom(fromMail);
            // 设置收件人 一个或多个
            helper.setTo(toEmail.split(","));
            // 设置邮件标题
            helper.setSubject(emailTitle);
            // 设置邮件内容 开启 html 格式
            helper.setText(emailContent, true);
            // 设置邮件发送时间
            helper.setSentDate(new Date());
            // 发送邮件
            mailSender.send(message);
            log.info("邮件发送成功 -> {}", toEmail);
        } catch (MessagingException e) {
            log.error("邮件发送异常", e);
        }
    }
}
